package com.lucky.controller;

import com.lucky.annotation.Authority;
import com.lucky.pojo.vo.User;
import com.lucky.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import java.util.Collection;
import java.util.Random;

/**
 * @Description
 * @Author Jalyson
 * @Version V1.0.0
 * @Since 1.0
 * @Date 2019/6/27
 */
@Controller
@RequestMapping("/user")
public class UserController {
    /** logger */
    private static final Logger LOGGER = LoggerFactory.getLogger(UserController.class);
    @Resource(name = "userService")
    private UserService userService;

    @RequestMapping("/addUser")
    public ModelAndView addUser(@RequestParam(defaultValue = "5") Integer size) {
        Random random = new Random();
        for (int i = 0; i < 5; i++) {
            User user = new User();
            user.setAge(30 + (random.nextInt(1000) % 5));
            user.setUsername("Jalyson" + random.nextInt(1000));
            user.setPassword("Jalyson" + random.nextInt(1000));
            if(i%2==0){
                user.setRole("manager");
            }else{
                user.setRole("admin");
            }
            user.setBrief("haha.");
            userService.save(user);
        }
        ModelAndView model = new ModelAndView("redirect:/home");
        model.addObject("info", "操作成功!");
        return model;
    }

    @RequestMapping("/view/{id}")
    @ResponseBody
    public User view(@PathVariable Long id) {
        User user = userService.get(id);
        return user;
    }

    @Deprecated
    @RequestMapping("/remove/{id}")
    @ResponseBody
    public ModelAndView remove(@PathVariable Long id) {
        ModelAndView model = new ModelAndView("redirect:/home");
        if (userService.remove(id)) {
            model.addObject("info", "删除成功!");
        } else {
            model.addObject("info", "删除成功!");
        }
        return model;
    }

    @Authority(role = { "manager" })
    @RequestMapping("/list")
    @ResponseBody
    public Collection<User> getData() {
        Collection<User> all = userService.findAll();
        return all;
    }

    @RequestMapping("/{id}")
    @ResponseBody
    public User get(@PathVariable Long id) {
        return userService.get(id);
    }
}
